import React from 'react'
import * as Icon from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { useDispatch,useSelector } from 'react-redux';
import { selectMenuList } from '../../store/reducer/tab';

import { Menu , Layout  } from 'antd';

import MenuConfig from '../../config' 

const { Sider } = Layout;

// 动态获取icon
const itemToElement=(name)=>React.createElement(Icon[name])

// 处理菜单数据
const items=MenuConfig.map((item)=>{
    // 没有子菜单
    const child={
        key:item.path,
        icon:itemToElement(item.icon),
        label:item.label
    }
    // 有子菜单
    if(item.children){
        child.children = item.children.map(item=>{
            return {
                key:item.path,
                label:item.label
            }
        })
    }
    return child
})

export default function CommonAside({collapsed}) {
    // console.log(collapsed);
    const navigate = useNavigate()
    const dispatch = useDispatch()
    const currentMenuPath = useSelector(state=>state.tab.currentMenu.path)

    // 添加数据到store
    const setTabList = (val) =>{
        dispatch(selectMenuList(val))
    }

    // 点击菜单
    const selectMenu=(e)=>{
        console.log(e);
        let data
        MenuConfig.forEach(item=>{
            // 通过path匹配
            if(item.path === e.keyPath[e.keyPath.length-1]){
                data = item
                // 如果存在二级路由，匹配其父路由
                if(e.keyPath.length>1){
                    data = item.children.find(child=>{
                        return child.path === e.key 
                    })
                }
            }
        })
        setTabList({
            path:data.path,
            name:data.name,
            label:data.label
        })
        navigate(e.key)
    }
    return (
        <Sider trigger={null} collapsed={collapsed}>
            <h3 className='app-name'>{collapsed?'后台':'通用后台管理系统'}</h3>
            <Menu
                theme="dark"
                mode="inline"
                defaultSelectedKeys={['/home']}
                items={items}
                style={{
                    height: '100%'
                }}
                onClick={selectMenu}
                selectedKeys={[!currentMenuPath ? '/home' : currentMenuPath]}
            />
        </Sider>
    )
}
